package com.yan.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 网关登录拦截处理
 *
 * @Author: 汪焰
 * @Date: 2021/3/28 16:55
 */
@Slf4j
//@Component//让容器扫描到 等于注册了
public class LoginFilter implements GlobalFilter, Ordered {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 过滤器封装了核心方法
     *
     * @Author: 汪焰
     * @Date: 2021/3/28 16:56
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //从上下文中获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        String clientIp = request.getRemoteAddress().getHostString();
        //从cookie中获取token
        HttpCookie token = request.getCookies().getFirst("token");
        if (token != null && token.getValue() != null) {
            String tokenValue = token.getValue();
            Object email = restTemplate.getForObject("http://localhost:8080/user/info/" + tokenValue, Object.class);
            if (email != null) {
                String url = "http://www.test.com/static/welcome.html?email=" + email;
                ServerHttpResponse response = exchange.getResponse();
                //303状态码表示由于请求对应的资源存在着另一个URI，应使用GET方法定向获取请求的资源
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().set(HttpHeaders.LOCATION, url);
                return response.setComplete();
            }
        }
        System.out.println("gateway LoginFilter 没问题");
        return chain.filter(exchange);
    }

    /**
     * 返回值表示当前过滤器的顺序（优先级），数值越小，优先级越高
     *
     * @Author: 汪焰
     * @Date: 2021/3/28 16:57
     */
    @Override
    public int getOrder() {
        return 5;
    }
}
